package com.tgy.set;

import java.util.LinkedList;
import java.util.List;

/**
 * @Author: tgy
 * @Date: 2020-09-22 16:18
 */
public class LinkedSet<E> implements Set<E> {

    private LinkedList<E> list = new LinkedList<>();

    @Override
    public int size() {
        return list.size();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public void clear() {

        list.clear();
    }

    @Override
    public boolean contains(E element) {

        return list.contains(element);
    }

    @Override
    public void add(E element) {

        int indexOf = list.indexOf(element);

        if (indexOf == -1) {
        // 不存在就添加
            list.add(element);
        }else {
        // 存在替换
            list.set(indexOf,element);
        }

    }

    @Override
    public void remove(E element) {

        list.remove(element);
    }

    @Override
    public void traversal(Visitor<E> visitor) {

        for (int i = 0; i < list.size(); i++) {

            if (visitor.visit(list.get(i))) {

                return;
            }
        }

    }
}
